package com.us.example.service;

import com.prometheus.serial.Serial;
import com.prometheus.serial.exception.SerialPortParameterFailure;
import com.us.example.bean.Message;

/**
 * Created by yangyibo on 17/1/12.
 */

import com.us.example.bean.Response;

import gnu.io.SerialPort;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import org.openmuc.jmbus.MBusSap;
import org.openmuc.jmbus.ScanSecondaryAddress;
import org.openmuc.jmbus.VariableDataStructure;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

@Service
public class WebSocketService {
	
	public static boolean RUNNING=true;

    @Autowired
    //使用SimpMessagingTemplate 向浏览器发送消息
    private SimpMessagingTemplate template;

    public void sendMessage(Message message) throws Exception{
        System.out.println();
        System.out.println("Scan finished.");
        RUNNING=true;

        MBusSap mBusSap = new MBusSap("COM5", 2400);
        try {
            mBusSap.open();
            mBusSap.setTimeout(3000);

            do {
            	scanPrimaryAddresses(mBusSap,message.getStart(),message.getEnd());
            }while(RUNNING);
            mBusSap.close();
            sendToClient("Closing....");

        } catch (IOException e2) {
            System.out.println("Failed to open serial port: " + e2.getMessage());
            return;
        } finally {
            mBusSap.close();
        }
    
 
    }
    
   private  void scanPrimaryAddresses(MBusSap mBusSap,int min,int max) {

        for (int i = min; i <=max; i++) {

        	sendToClient("primary address is scaning "+i,i,0,"");
            try {
            	VariableDataStructure msg=mBusSap.read(i);
            	sendToClient(msg.toString(),i,msg.getStatus(),msg.getStatusInfo());
            	 try {
                    Thread.sleep(5000); // for slow slaves
                } catch (InterruptedException e) {
                	System.out.println("Thread sleep fails.\n" + e.getMessage());
                }
              
             
            } catch (TimeoutException e) {
                continue;
            } catch (IOException e) {
                System.out.println();
                System.out.println("Error reading meter at primary address " + i + ": " + e.getMessage());
                System.out.print("Scanning address: ");
                continue;
            }
            System.out.println();
            sendToClient("Found device at primary address " + i + ".");
            System.out.print("Scanning address: ");
        }
    }
   
   private void test() throws SerialPortParameterFailure, Exception {
	   
	   Serial serial=new Serial(2400, 8, 1, SerialPort.PARITY_EVEN, 2000);
		
		serial.setDebug(true);
		//serial.addListener();
		serial.openPort("COM5");

		
		byte[] data=Serial.getByteArrayBySize(8);
		 
		//Secondary Address
		data[3]=(byte)0x71;
		data[2]=(byte)0x10;
		data[1]=(byte)0x00;
		data[0]=(byte)0x48;
		data[4]=(byte)0xff;
		data[5]=(byte)0xff;
		data[6]=(byte)0xff;
		data[7]=(byte)0xff;
		
	
		serial.readoutMeter(data);

   }
   
   
   private void sendToClient(String msg) {
	   template.convertAndSend("/topic/getResponse",new Response(msg));
	   System.out.println(msg);
   }

   
   private void sendToClient(String msg,int addr,int status,String info) {
	   Response rsq=new Response(msg);
	   rsq.setAddr(addr);
	   rsq.setStatus(status);
	   rsq.setStatusInfo(info);
	   template.convertAndSend("/topic/getResponse",rsq);
	   System.out.println(msg);
   }


}
